import random

from django.core.cache import cache
from django.db import models
from django.conf import settings

# Create your models here. 砍价APP
from django.db.models import Sum
from django.urls import reverse
from django.utils import timezone

from account.models import User
from common.models import Common, MusicInfo, CommonSocial
from shop.models import ShopInfo


class KanjiaInfo(Common, CommonSocial):
    """砍价项目"""
    shop = models.ForeignKey(ShopInfo, verbose_name=u'店铺', null=True, on_delete=models.SET_NULL, related_name='kj_shop')

    title = models.CharField(u'标题', max_length=100)
    start_time = models.DateTimeField(u'活动开始时间')
    end_time = models.DateTimeField(u'活动截止时间')
    price_original = models.IntegerField(u'原价(分)', default=0)
    price_discount = models.IntegerField(u'底价(分)', default=0)

    sub_price_min = models.IntegerField(u'最少减价(分)', default=0)
    sub_price_max = models.IntegerField(u'最多减价(分)', default=0)
    sub_time = models.IntegerField(u'砍价时间间隔(小时)', default=0)
    top_image = models.CharField(u'图片', max_length=100, default='', blank=True)
    qrcode4xcx = models.CharField(u'小程序二维码', max_length=200, default='', blank=True)
    shelve = models.BooleanField(u'上架', default=False, help_text=u'False为下架，True为上架')
    music = models.ForeignKey(MusicInfo, verbose_name=u'背景音乐', on_delete=models.SET_NULL, null=True, blank=True)
    desc = models.TextField(u'富文本描述', default='')
    inventory = models.IntegerField(u'库存', default=100)

    class Meta:
        db_table = 'kanjia_info'
        verbose_name = u'砍价活动'
        ordering = ['-create_time']

    def get_image_url(self):
        return settings.QINIU_DOMAIN + self.top_image

    def get_mobile_url(self):
        return 'http://qxb.dongpouu.com%s?shop=%s' % (reverse('wehelp:join', args=[self.id]), self.shop_id)

    def has_start(self):
        return self.start_time < timezone.now()

    def has_end(self):
        return self.end_time < timezone.now()

    def get_music_url(self):
        if self.music:
            return self.music.get_path_url()
        return ''

    def get_inventory(self):
        return self.inventory - self.sale


class KanJiaUserMaster(Common):
    """报名用户"""
    user = models.ForeignKey(User, verbose_name=u'用户', related_name='kanjia_master', on_delete=models.CASCADE)
    superior = models.ForeignKey(User, verbose_name=u'来源', null=True, blank=True, related_name='kjum_superior',
                                 on_delete=models.SET_NULL)
    info = models.ForeignKey(KanjiaInfo, verbose_name=u'砍价产品', related_name='info_set', on_delete=models.CASCADE)
    name = models.CharField(u'姓名', max_length=25, default='', blank=True)
    phone = models.CharField(u'手机号', max_length=25, default='', blank=True)
    real_price = models.IntegerField(u'实际价格(分)', default=0, blank=True)
    has_consume = models.BooleanField(u'是否领奖', default=False, help_text=u'False为未领奖，True为已领奖')
    cash_time = models.DateTimeField(u'兑换时间', null=True, blank=True)
    order = models.ForeignKey('order.Order', verbose_name=u'订单记录', null=True, blank=True, on_delete=models.SET_NULL)
    refund = models.ForeignKey('order.RefundOrder', verbose_name=u'退单记录', null=True, blank=True,
                               on_delete=models.SET_NULL)
    help_count = models.IntegerField(u'帮减人数迁移', default=0)

    def __unicode__(self):
        return str(self.id)

    def get_random_price(self):
        value = random.randint(self.info.sub_price_min, self.info.sub_price_max)
        _price = self.get_price_discount() - self.info.price_discount
        if value >= _price:
            value = _price
        return value

    def price_cache_key(self):
        return 'KANJIA.KANJIAMASTER.%s' % self.id

    def set_price_cache(self):
        cache_key = self.price_cache_key()
        price = self.info.price_original - (
                self.master_set.filter(status=KanJiaUserMem.STATUS_VALID).aggregate(Sum('sub_price')).get(
                    'sub_price__sum') or 0)
        if price <= self.info.price_discount:
            price = self.info.price_discount
        cache.set(cache_key, price)
        if not self.real_price == self.info.price_discount:
            self.real_price = price
            self.save()
        return price

    def get_price_discount(self):
        if self.info.has_end():
            return self.real_price
        cache_key = self.price_cache_key()
        price = cache.get(cache_key)
        if not price:
            return self.set_price_cache()
        return price

    def get_helper_count(self):
        return self.help_count

    class Meta:
        unique_together = ('user', 'info')
        db_table = 'kanjia_master'
        verbose_name = u'报名用户'
        ordering = ['-create_time']


class KanJiaUserMem(Common):
    """砍价用户"""
    user = models.ForeignKey(User, verbose_name=u'帮砍用户', related_name='kanjia_member', on_delete=models.CASCADE)
    master = models.ForeignKey(KanJiaUserMaster, verbose_name=u'报名用户', related_name='master_set',
                               on_delete=models.CASCADE)
    sub_price = models.IntegerField(u'砍价金额（分）')

    def __unicode__(self):
        return str(self.id)

    def master_can_serve_for_self(self):
        return timezone.now() >= self.create_time + timezone.timedelta(minutes=self.master.info.sub_time)

    def get_sub_price(self):
        return self.sub_price / 100.00

    class Meta:
        index_together = ['master', 'user']
        db_table = 'kanjia_member'
        verbose_name = u'砍价记录'
        ordering = ['-create_time']
